package com.aaa.dao.impl;

import com.aaa.dao.BaseDao;
import com.aaa.dao.StudentDao;
import com.aaa.entity.Pager;
import com.aaa.entity.StudentEntity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class StudentDaoImpl extends BaseDao implements StudentDao {
    @Override
    public Pager query(int curPage, int pageSize, Map condition) {
        String sql="select a.*,b.classname FROM student a LEFT JOIN class b on a.classid=b.classid where 1=1 and a.del_flag=0 ";
        StringBuffer buffer=new StringBuffer(sql);
        List params=new ArrayList();

        if (condition!=null)
        {
            if (condition.containsKey("stuname")&&condition.get("stuname").toString().length()>0)
            {
                buffer.append("and stuname like ?");
                params.add("%"+condition.get("stuname")+"%");
            }
            if (condition.containsKey("sex")&&condition.get("sex").toString().length()>0)
            {
                buffer.append("and sex like ?");
                params.add("%"+condition.get("sex")+"%");
            }
            if (condition.containsKey("classname")&&condition.get("classname").toString().length()>0)
            {
                buffer.append("and classname like ?");
                params.add("%"+condition.get("classname")+"%");
            }
        }

        sql="select count(*) c from ("+buffer+") stu";
        List<Map> map=this.executeQuery(sql,params.toArray());
        Long count=(long)map.get(0).get("c");

        buffer.append("limit ?,?");
        int startIndex=(curPage-1)*pageSize;
        params.add(startIndex);
        params.add(pageSize);
        List<Map> list=this.executeQuery(buffer.toString(),params.toArray());

        Pager pager=new Pager(curPage,pageSize,list,count.intValue());
        return pager;
    }

    @Override
    public int create(StudentEntity info) {
        String sql="insert into student (stuname,sex,phone,stutate,remark) value(?,?,?,?,?)";
        return this.executeInsert(sql,info.getStuname(),info.getSex(),info.getPhone(),info.getStutate(),info.getRemark());
    }

    @Override
    public int update(StudentEntity info) {
        String sql="update student set stuname=?,sex=?,phone=?,stutate=?,remark=? WHERE stuid=?";
        return this.executeUpdate(sql,info.getStuname(),info.getSex(),info.getPhone(),info.getStutate(),info.getRemark(),info.getStuid());
    }

    @Override
    public int delete(int stuid) {
        String sql="update student set del_flag=1 where stuid=?";
        return this.executeUpdate(sql,stuid);
    }

    @Override
    public Map queryid(int stuid) {
        String sql="select * from student where stuid=?";
        List<Map> list=this.executeQuery(sql,stuid);
        return list.size()>0?list.get(0):null;
    }
}
